// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userAddress:{},
    goodsList:[],
    choseAll:false,
    allPrice:0,
    choseNum:0
  },
  cartList:[],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  onShow(options){
    const address =wx.getStorageSync('address');
    const goods =wx.getStorageSync('cart');
    this.cartList =goods;
    this.setData({
      userAddress:address,
      goodsList:goods,
    })
    this.jiSuanAllPrice();   

  },
  // 获取收货地址
  handleAddress() {
    wx.chooseAddress({
      success: (result) => {
        console.log(result);
        wx.setStorageSync('address', result);
        this.setData({
          userAddress:result
        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },

  //加减数量
  handleGoodsNum(e){   
    this.cartList =this.data.goodsList;
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    const num =this.cartList[index].num;
    if(type==2){
      this.cartList[index].num++;
    }else{
      if(num===1){
       this.cartList.splice(index,1);
      }else{
        this.cartList[index].num--;
      }
    }

   wx.setStorageSync('cart', this.cartList);
    this.setData({
      goodsList:this.cartList
    })
    this.jiSuanAllPrice();
  },
  // 选择了其中的一个商品
  handleChoseGoods(e){
    this.cartList =this.data.goodsList;
    const index =e.currentTarget.dataset.index;
    this.cartList[index].is_promote =!this.cartList[index].is_promote;
    wx.setStorageSync('cart', this.cartList);
    this.setData({
      goodsList:this.cartList
    })
    console.log(this.cartList);
    this.jiSuanAllPrice();
  },

  handleChoseAllGoods(){
    const isChose =!this.data.choseAll;
    this.cartList =this.data.goodsList;
    for (let i = 0; i < this.cartList.length; i++) {
      this.cartList[i].is_promote =isChose;      
    }
    this.setData({
      goodsList:this.cartList,
      choseAll:isChose
    })
    this.jiSuanAllPrice();
  },

// 计算总价
jiSuanAllPrice(){
  var isChose =true;
  var price =0;
  var num =0;
  // 遍历 this.cartList.every(v=>v.is_promote);

  for (let i = 0; i < this.cartList.length; i++) {
    if(this.cartList[i].is_promote===true){
      price =price+this.cartList[i].goods_price*this.cartList[i].num;
      num =num+this.cartList[i].num;
    }else{
      isChose =false;
    }
  }
this.setData({
  choseAll:isChose,
  allPrice:price,
  choseNum:num
})
},

// 结算
handleJieSan(){
  const {userAddress} =this.data
  if (!userAddress.userName) {
    wx.showToast({
      title: '请选择收货地址',
      duration: 1500,
      icon: 'none',
      mask: true,
    })
    return;
  }
  if (this.data.choseNum===0) {
    wx.showToast({
      title: '请选择商品',
      duration: 1500,
      icon: 'none',
      mask: true,
    })
    return;
  }
wx.navigateTo({
  url: '/pages/pay/index',
});
  

}


})